package down.sallai.ml.util.wx;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @description: $
 * @author: sallai
 * @time: 2022年1月5日 0005 下午 08:42:30 秒
 */
@Slf4j
@Component
public class GithubVerity {
    public final static int CODE_LEN = 5;
    private final static int RESET_COUNT = 3;
    @Autowired
    RedisTemplate redisTemplate;

    public  String setVerity(){
        String code = generateCode();
        boolean res = redisTemplate.opsForValue().setIfAbsent(code,0,5, TimeUnit.MINUTES);
        int count = 0;
        while(!res && count < RESET_COUNT) {
            log.debug("add redis fail maybe is code repeate count:"+count);
            code = generateCode();
            res = redisTemplate.opsForValue().setIfAbsent(code,0,5, TimeUnit.MINUTES);
            count++;
        }
        if(res) {
            return code;
        }else{
            return "";
        }
    }


    /**
     * 生成权限码
     * @return
     */
    public  String generateCode(){
        Random random = new Random();
        String code = "";
        for (int i = 0; i < CODE_LEN ;i++) {
            code += random.nextInt(10);
        }
        log.info("生成权限码->"+code);
        return code;
    }
}
